package com.ruoyi.mall.app.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.mall.app.domain.CouponCheckRequest;
import com.ruoyi.mall.app.domain.GoodsInfo;
import com.ruoyi.mall.app.service.DtsCouponService;
import com.ruoyi.mall.common.domain.DtsCoupon;
import com.ruoyi.mall.common.domain.DtsCouponUser;
import com.ruoyi.mall.common.domain.DtsUserCouponVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/user/coupon")
public class DtsCouponController extends BaseController {

    @Autowired
    private DtsCouponService couponService;


    // 获取用户优惠券列表
    @GetMapping("/list")
    public AjaxResult list(Long userId,
            @RequestParam(defaultValue = "0") Integer status) {

        List<DtsUserCouponVo> list = couponService.getUserCouponList(userId, status);
        if (list != null){
            return success(list);
        }else {
            return error();
        }
    }

    // 使用优惠券
    @GetMapping("/use")
    public AjaxResult useCoupon(DtsCouponUser dtsCouponUser) {

        return toAjax(couponService.useCoupon(dtsCouponUser));
    }


    //可用优惠卷数量
    @GetMapping("/number")
    public AjaxResult getCouponCount(Long userId) {
        int count = couponService.getCouponCount(userId);
        return success(count);
    }

    // 获取可领取优惠券列表
    @GetMapping("/available")
    public AjaxResult availableCoupons(Long userId) {
        List<DtsCoupon> list = couponService.getAvailableCoupons(userId);
        if (list != null) {
            return success(list);
        } else {
            return error();
        }
    }
    //可领取优惠券
    @GetMapping("/receive")
    public AjaxResult receiveCoupon(Long userId, Long couponId) {
        try {
            int result = couponService.receiveCoupon(userId, couponId);
            return result > 0 ? AjaxResult.success() : AjaxResult.error();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    // 优惠卷返还
    @GetMapping("/returnCoupon")
    public AjaxResult returnCoupon(DtsCouponUser dtsCouponUser) {
        return toAjax(couponService.refundCoupon(dtsCouponUser));
    }

    @GetMapping("/checkScope")
    public AjaxResult checkCouponScope(
            @RequestParam Long couponId,
            @RequestParam String goodsList) {

        try {
            DtsCoupon coupon = couponService.getCouponById(couponId);
            if (coupon == null) {
                return AjaxResult.error("优惠券不存在");
            }

            // 解析商品列表字符串
            ObjectMapper mapper = new ObjectMapper();
            List<GoodsInfo> goodsInfoList = mapper.readValue(goodsList, new TypeReference<List<GoodsInfo>>() {});

            // 1. 检查商品范围
            boolean isValid = false;
            String reason = "";

            if (coupon.getGoodsType() == 1) { // 类目限制
                List<Long> categoryIds = goodsInfoList.stream()
                        .map(GoodsInfo::getCategoryId)
                        .collect(Collectors.toList());

                List<Long> allowedCats = parseIds(coupon.getGoodsValue());
                isValid = categoryIds.stream().anyMatch(allowedCats::contains);

                if (!isValid) {
                    reason = "仅限指定类目商品使用";
                }
            }
            else if (coupon.getGoodsType() == 2) { // 商品限制
                List<Long> goodsIds = goodsInfoList.stream()
                        .map(GoodsInfo::getId)
                        .collect(Collectors.toList());

                List<Long> allowedGoods = parseIds(coupon.getGoodsValue());
                isValid = goodsIds.stream().anyMatch(allowedGoods::contains);

                if (!isValid) {
                    reason = "仅限指定商品使用";
                }
            }
            else { // 全商品可用
                isValid = true;
            }

            // 2. 返回校验结果
            CouponCheckResult result = new CouponCheckResult();
            result.setValid(isValid);
            result.setReason(reason);

            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("校验失败: " + e.getMessage());
        }
    }

    // 辅助方法：解析ID列表
    private List<Long> parseIds(String ids) {
        if (ids == null || ids.isEmpty()) {
            return null;
        }
        return Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
    }
}


// 校验结果对象
class CouponCheckResult {
    private boolean valid;
    private String reason;

    // getters & setters
    public boolean isValid() { return valid; }
    public void setValid(boolean valid) { this.valid = valid; }
    public String getReason() { return reason; }
    public void setReason(String reason) { this.reason = reason; }
}


























